/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cenluan.photo;

import java.util.List;

import com.cenluan.common.OssManager;
import com.cenluan.gallery.Gallery;
import com.cenluan.user.User;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 照片
 * 
 * @author peak
 * 
 */
public class Photo extends Model<Photo> {

	private static final long serialVersionUID = 1L;
	public static final Photo dao = new Photo();

	/**
	 * 获取图片地址
	 * 
	 * @return
	 */
	public String getUrl() {
		return OssManager.getImageUrl(getStr("key"));
	}

	/**
	 * 获取所属相册
	 * 
	 * @return
	 */
	public Gallery getGallery() {
		return Gallery.dao.findById(getStr("galleryId"));
	}

	/**
	 * 获取创建者
	 * 
	 * @return
	 */
	public User getCreater() {
		return User.dao.findById(getStr("createrId"));
	}

	/**
	 * 添加查看过的用户
	 * 
	 * @param userId
	 */
	public boolean addView(String userId) {
		Record record = new Record();
		record.set("photoId", getStr("id"));
		record.set("userId", userId);
		return Db.save("t_photo_view", record);
	}

	/**
	 * 判断用户是否查看过
	 * 
	 * @param userId
	 * @return
	 */
	public boolean hasViewed(String userId) {
		return Db.queryLong("select count(*) from t_photo_view "
				+ "where photoId=? and userId=?", getStr("id"), userId) == 1;
	}

	/**
	 * 添加收藏
	 * 
	 * @param userId
	 * @return
	 */
	public boolean addFavorite(String userId) {
		Record record = new Record();
		record.set("photoId", getStr("id"));
		record.set("userId", userId);
		return Db.save("t_photo_favorite", record);
	}

	/**
	 * 取消收藏
	 * 
	 * @param userId
	 * @return
	 */
	public boolean removeFavorite(String userId) {
		return Db.update("delete from t_photo_favorite "
				+ "where photoId=? and userId=?", getStr("id"), userId) == 1;
	}

	/**
	 * 是否已收藏
	 * 
	 * @param userId
	 * @return
	 */
	public boolean hasFavorited(String userId) {
		return Db.queryLong("select count(*) from t_photo_favorite "
				+ "where photoId=? and userId=?", getStr("id"), userId) == 1;
	}

	/**
	 * 分页查询照片
	 * 
	 * @param pn
	 * @param pz
	 * @param galleryId
	 *            相册Id
	 * @param order
	 *            排序，1代表按浏览人数倒序，2代表按收藏人倒序，其它默认按创建时间倒序
	 * @return
	 */
	public Page<Photo> page(int pn, int pz, String galleryId, int order) {
		StringBuilder sql = new StringBuilder();
		sql.append(" from t_photo p ");
		if (order == 1) {
			sql.append(" left join ( ");
			sql.append(" select count(*) ct,photoId ");
			sql.append(" from t_photo_view group by photoId ");
			sql.append(" ) pv on pv.photoId=p.id ");

		}
		if (order == 2) {
			sql.append(" left join ( ");
			sql.append(" select count(*) ct,photoId ");
			sql.append(" from t_photo_favorite group by photoId ");
			sql.append(" ) pf on pf.photoId=p.id ");
		}
		sql.append(" where p.galleryId=? ");
		if (order == 1) {
			sql.append(" order by pv.ct desc,p.createTime desc ");
		} else if (order == 2) {
			sql.append(" order by pf.ct desc,p.createTime desc ");
		} else {
			sql.append(" order by p.createTime desc ");
		}

		return paginate(pn, pz, "select p.*", sql.toString(), galleryId);

	}

	/**
	 * 获取id集合，便地显示当前图片是第几个，下一张的id等
	 * 
	 * @param galleryId
	 *            相册ID
	 * @param order
	 *            排序，1代表按浏览人数倒序，2代表按收藏人倒序，其它默认按创建时间倒序
	 * @return
	 */
	public List<String> getIdList(String galleryId, int order) {
		StringBuilder sql = new StringBuilder();
		sql.append("select p.id ");
		sql.append(" from t_photo p ");
		sql.append(" left join t_gallery_member gm ");
		sql.append(" on (gm.galleryId=p.galleryId and gm.userId=p.createrId) ");
		if (order == 1) {
			sql.append(" left join ( ");
			sql.append(" select count(*) ct,photoId ");
			sql.append(" from t_photo_view group by photoId ");
			sql.append(" ) pv on pv.photoId=p.id ");

		}
		if (order == 2) {
			sql.append(" left join ( ");
			sql.append(" select count(*) ct,photoId ");
			sql.append(" from t_photo_favorite group by photoId ");
			sql.append(" ) pf on pf.photoId=p.id ");
		}
		sql.append(" where (gm.active is null or gm.active=1) and p.galleryId=? ");
		if (order == 1) {
			sql.append(" order by pv.ct desc,p.createTime desc ");
		} else if (order == 2) {
			sql.append(" order by pf.ct desc,p.createTime desc ");
		} else {
			sql.append(" order by p.createTime desc ");
		}
		return Db.query(sql.toString(), galleryId);
	}

	/**
	 * 获取浏览次数
	 * 
	 * @return
	 */
	public long getViewCount() {
		return Db.queryLong("select count(*) from t_photo_view"
				+ " where photoId=?", getStr("id"));
	}

	/**
	 * 获取收藏总数
	 * 
	 * @return
	 */
	public long getFavoriteCount() {
		return Db.queryLong("select count(*) from t_photo_favorite"
				+ " where photoId=?", getStr("id"));
	}

	/**
	 * 先删除关联数据，再删除照片本身
	 */
	@Override
	public boolean delete() {
		Db.update("delete from t_photo_view where photoId=?", getStr("id"));
		Db.update("delete from t_photo_favorite where photoId=?", getStr("id"));
		OssManager.deleteImage(getStr("key"));
		return super.delete();
	}
}
